<template>
  <div class="orderDetails_container" v-loading="loading">
    <h1>订单状态：
      <dict-tag :options="dict.type.order_order_status" :value="order.orderStatus" />
    </h1>
    <el-divider></el-divider>
    <div class="orderDetails-orderInfo">
      <h2>买家信息:</h2>
      <span>登录账号：{{order.memberName}}</span>
      <span>客户名称：{{order.purchaserName}}</span>
      <span>收货人名称：{{order.consigneeName}}</span>
      <span>收货电话：{{order.consigneeMobile}}</span>
      <span>收件地址：{{order.consigneeProvince + order.consigneeCity + order.consigneeCounty + order.consigneeDetail}}</span>
    </div>
    <div class="orderDetails-orderInfo">
      <h2>支付与配送信息:</h2>
      <span class="dict-tag"> 支付方式： {{
        order.paymentMethod === 'WECHAT' ? '微信支付' :
        order.paymentMethod === 'ALIPAY' ? '支付宝支付' :
        order.paymentMethod === 'DINPAY' ? '智付' :
        order.paymentMethod === 'WALLET' ? '账户余额' :
        order.paymentMethod === 'BANK_TRANSFER' ? '线下公账交易' : ''        }}
      </span>
      <span class="dict-tag"> 支付通道： {{
        order.paymentChannel === 'WECHAT' ? '微信支付' :
        order.paymentChannel === 'ALIPAY' ? '支付宝支付' :
        order.paymentChannel === 'DINPAY' ? '智付' :
        order.paymentChannel === 'WALLET' ? '账户余额' :
        order.paymentChannel === 'BANK_TRANSFER' ? '线下公账交易' : ''        }}
      </span>
      <span class="dict-tag"> 支付状态：
        <dict-tag :options="dict.type.order_pay_status" :value="order.payStatus" />
      </span>
      <span>送货方式：快递/物流</span>
      <span>物流公司：{{order.logisticsName}}</span>
      <span>物流单号：{{order.logisticsNo}}</span>
    </div>
    <div class="orderDetails-orderInfo">
      <h2>订单信息:</h2>
      <span>订单编号：{{order.sn}}</span>
      <span>创建日期：{{order.createTime}}</span>
      <p>卖家留言：{{order.remark}}</p>
    </div>

    <div class="tableOrderList">
      <h3>商品清单:</h3>
      <el-table border :data="order.orderItems" border style="width: 100%">
        <el-table-column label="序号" align="center" type="index"> </el-table-column>
        <el-table-column label="商品编码" align="center" prop="identifier">
          <template slot-scope="scope">
            <div>
              {{ scope.row.identifier }}<span style="color: red; font-size: 10px;"
                v-if="scope.row.ephedrine">麻</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="商品名称" width="200" align="center" prop="name"> </el-table-column>
        <el-table-column label="生产企业" width="200" align="center" prop="manufacturer">
        </el-table-column>
        <el-table-column label="商品规格" align="center" prop="simpleSpecs"> </el-table-column>
        <el-table-column label="活动" align="center" prop="promotionType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.app_promotion_type" :value="scope.row.promotionType" />
          </template>
        </el-table-column>
        <el-table-column label="商品原价" align="center" prop="unitPrice"> </el-table-column>
        <el-table-column label="销售价格" align="center" prop="goodsPrice"> </el-table-column>
        <el-table-column label="订购数量" align="center" prop="num">
          <template slot-scope="scope">
            <div :style="{ color: scope.row.num > scope.row.quantity ? 'red' : 'black' }">
              {{ scope.row.num }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="出库数量" align="center" prop="outboundNum"> </el-table-column>
        <el-table-column label="小计" align="center" prop="subTotal">
          <template slot-scope="scope">
            {{(scope.row.goodsPrice * scope.row.num).toFixed(2)}}
          </template>
        </el-table-column>
      </el-table>
      <div class="p">
        <span>商品金额：{{order.goodsPrice}}</span>
        <span>配送费用：{{order.freightPrice}}</span>
        <span>优惠金额：{{order.discountPrice}}</span>
        <span>优惠券金额：{{order.couponPrice}}</span>
        <span>支付金额：{{order.flowPrice}}</span>
      </div>
    </div>

    <div class="issueOrderList" v-if="order.innerStatus === 'PACKAGED'">
      <el-divider></el-divider>
      <h3>出库单号: {{issue.outboundOrderItems[0].outboundOrderSn}}</h3>
      <el-table border v-loading="loading" :data="issue.outboundOrderItems" border
        style="width: 100%">
        <el-table-column label="序号" align="center" type="index"> </el-table-column>
        <el-table-column label="商品编号" align="center" prop="identifier">
        </el-table-column>
        <el-table-column label="商品名称" width="450" align="center" prop="goodsName">
        </el-table-column>
        <el-table-column label="生产企业" width="450" align="center" prop="manufacturer">
        </el-table-column>
        <el-table-column label="商品规格" align="center" prop="simpleSpecs"> </el-table-column>
        <el-table-column label="有效期至" align="center" prop="expiryDate"> </el-table-column>
        <el-table-column label="销售价格" align="center" prop="goodsPrice"> </el-table-column>
        <el-table-column label="出库数量" align="center" prop="num"> </el-table-column>
        <el-table-column label="小计" align="center" prop="subTotal"> </el-table-column>
      </el-table>
      <div class="p">
        <span class="dict-tag">支付状态：
          <dict-tag :options="dict.type.order_pay_status" :value="order.payStatus" />
        </span>
        <span>出库单金额：{{issue.flowPrice}}</span>
      </div>
    </div>

    <div class="order_status">
      <!-- 未支付 -->
      <div
        v-if="(order.payStatus === 'UNPAID' || order.payStatus === 'UNDETERMINED') && (order.orderStatus === 'UNPAID' || order.orderStatus === 'CANCELLED')">
        <!-- 选择支付方式 -->
        支付方式：
        <el-select v-model="valuetype" style="width:150px">
          <el-option v-for="item in options" :key="item.value" :label="item.name"
            :value="item.method">
          </el-option>
        </el-select>
        <!-- 支付单号 -->
        流水号：<el-input v-model="payOrderNumber" style="width:250px;margin:30px 0">
        </el-input>
      </div>

      <!-- 未发货 -->
      <div v-if="order.orderStatus === 'UNDELIVERED'">
        <!-- 物流公司 -->
        物流公司：
        <el-select v-model="valuetype" style="width:150px">
          <el-option v-for="(item,index) in options" :key="index" :label="item.name"
            :value="item.code">
          </el-option>
        </el-select>
        <!-- 物流单号 -->
        物流单号：<el-input v-model="payOrderNumber" style="width:250px;margin:30px 0"></el-input>
      </div>

      <!-- 订单 取消 -->
      <el-button type="danger" @click="orderCancel" v-hasPermi="['order:order:cancel']"
        :disabled="order.orderStatus != 'UNPAID' ">
        取消订单
      </el-button>

      <!-- 订单 支付待确认 -->
      <!--
      <el-button type="primary" @click="unpayed" :disabled="order.payStatus !== 'UNDETERMINED'"
        v-hasPermi="['order:order:payment:edit']">
        未支付
      </el-button>
      -->

      <!-- 订单 未支付 -->
      <el-button type="primary" @click="payed"
        :disabled="order.orderStatus !== 'UNPAID' && order.orderStatus !== 'CANCELLED'"
        v-hasPermi="['order:order:payment:edit']">
        已支付
      </el-button>

      <!-- 订单 未发货 -->
      <el-button type="success" @click="shipped" :disabled="order.orderStatus !== 'UNDELIVERED'"
        v-hasPermi="['order:order:deliver:edit']">
        已发货
      </el-button>

      <!-- 订单 未收货 -->
      <!-- :disabled="order.orderStatus !== 'DELIVERED'" -->
      <el-button type="warning" @click="completed" v-hasPermi="['order:order:status:edit']"
        :disabled="order.orderStatus === 'COMPLETED' ">
        已收货
      </el-button>

      <!-- 订单退款 -->
      <el-button type="danger" @click="openOrderRefundView" v-hasPermi="['order:afterSale:add']"
        :disabled="order.payStatus != 'PAID' && order.payStatus != 'PARTIAL_REFUND'">
        退款
      </el-button>
    </div>

    <!-- 订单退款 的商品数量 -->
    <el-dialog v-dialogDragWidth v-dialogDragHeight v-dialogDrag title="提示"
      :visible.sync="orderRefundView" width="80%">
      <div class="tableOrderList">
        <h3>商品清单:</h3>
        <el-table border :data="afterSaleOrder.orderItems" border>
          <el-table-column label="序号" align="center" type="index"> </el-table-column>
          <el-table-column label="商品编码" align="center" prop="identifier" />
          <el-table-column label="商品名称" width="200" align="center" prop="name"> </el-table-column>
          <el-table-column label="生产企业" width="200" align="center" prop="manufacturer">
          </el-table-column>
          <el-table-column label="批准文号" width="150" align="center" prop="approvalNo">
          </el-table-column>
          <el-table-column label="商品规格" align="center" prop="simpleSpecs"> </el-table-column>
          <el-table-column label="销售价格" align="center" prop="goodsPrice"> </el-table-column>
          <el-table-column label="订购数量" align="center" prop="orderItemNum">
            <template slot-scope="scope">
              <font
                :style="{ color: scope.row.orderItemNum > scope.row.quantity ? 'red' : 'black' }">
                {{ scope.row.orderItemNum }}
              </font>
              <font v-if="scope.row.returnGoodsNumber > 0" style="color: coral;">
                -{{scope.row.returnGoodsNumber}}</font>
            </template>
          </el-table-column>
          <el-table-column label="出库数量" align="center" prop="outboundNum"> </el-table-column>
          <el-table-column label="退款数量" align="center" prop="num" width="150px">
            <template slot-scope="scope">
              <el-input-number style="width: 120px;" v-model="scope.row.num"
                @blur="refundNum(scope.row,scope.row.orderItemNum, scope.row.num)" :min="0"
                :max="scope.row.orderItemNum"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="小计" align="center" prop="subTotal">
            <template slot-scope="scope">
              {{(scope.row.goodsPrice * scope.row.num).toFixed(2)}}
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="p">
        <span>商品金额：{{afterSaleOrder.goodsPrice}}</span>
        <span>配送费用：{{afterSaleOrder.freightPrice}}</span>
        <span>优惠金额：{{afterSaleOrder.discountPrice}}</span>
        <span>优惠券金额：{{afterSaleOrder.couponPrice}}</span>
        <span>支付金额：{{afterSaleOrder.flowPrice}}</span>
        <span>退款金额：{{refundPrice}}</span>
        <span>退运费<el-checkbox v-model="refundFreightFlag"></el-checkbox></span>
        <el-button type="danger" size="mini" @click="fullRefund">整单退款</el-button>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="orderRefundView = false">取 消</el-button>
        <el-button type="primary" @click="orderRefund">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import {
  detailOrder
} from '@/api/order/offlineOrder.js'
import {
  getOrderInfos, getOrderIssueInfos, updOrderStatus, updOrderPayed, updateInnerStatus,
  getPayList, getLogisticsList, updLogistics, updUnpay, updPay, cancelOrder,
} from '@/api/order/order.js'
import { addAfterSale } from '@/api/order/afterSale.js'
import { listGoodsSku } from "@/api/goods/goods"

export default {
  name: 'OfflineOrderDetail',
  dicts: [
    "order_order_status",
    "order_pay_status",
    "order_payment_method",
    "app_promotion_type",
  ],
  data () {
    return {
      orderId: undefined,
      // 列表的行数据
      order: '',
      issue: '',
      loading: true,
      valuetype: '',
      options: [],
      payOrderNumber: '',
      orderRefundView: false,
      afterSaleOrder: {},
      refundFreightFlag: false,
      presentSkuList: [],
    }
  },
  computed: {
    refundPrice () {
      let a = 0
      for (const key in this.afterSaleOrder.orderItems) {
        if (this.afterSaleOrder.orderItems[key].num > 0) {
          a += this.afterSaleOrder.orderItems[key].num * this.afterSaleOrder.orderItems[key].goodsPrice
        }
      }

      //运费
      if (this.refundFreightFlag) {
        a += this.afterSaleOrder.freightPrice
      }

      return a.toFixed(2)
    },
  },
  created () {
    this.orderId = this.$route.params && this.$route.params.orderId;
    this.getOrderDetail()
  },
  methods: {
    fullRefund () {
      this.refundFreightFlag = true
      this.afterSaleOrder.orderItems.forEach(i => {
        i.num = i.orderItemNum
      })
    },
    refundNum (row, orderItemNum, num) {
      if (parseInt(orderItemNum) < parseInt(num)) {
        row.num = row.orderItemNum;
      }
    },
    getOrderDetail () {
      this.loading = true

      detailOrder(this.orderId).then(res => {
        if (res.code === 200) {
          this.order = res.data
          this.afterSaleOrder = this.deepCopy(this.order)
          this.afterSaleOrder.refundFreightFlag = false;

          this.loading = false;
          // 支付方式
          if (this.order.orderStatus === 'UNPAID' || this.order.orderStatus === 'CANCELLED') {
            getPayList().then(res => {
              if (res.code === 200) {
                this.options = res.data
                this.$delete(this.options, 3)
                this.valuetype = "BANK_TRANSFER"
              }
            })
          }
          // 物流公司
          if (this.order.orderStatus === 'UNDELIVERED') {
            getLogisticsList().then(res => {
              if (res.code === 200) {
                this.options = res.data
                this.valuetype = "JD"
              }
            })
          }
          // 出库单
          if (this.order.innerStatus === 'PACKAGED') {
            getOrderIssueInfos(this.order.id).then(reds => {
              if (reds.code === 200) {
                this.issue = reds.data
                this.issue.outboundOrderItems.forEach(outboundItem => {
                  this.order.orderItems.forEach(orderItem => {
                    if (!orderItem.outboundNum) {
                      orderItem.outboundNum = 0
                    }
                    if (orderItem.identifier == outboundItem.identifier && orderItem.goodsPrice == outboundItem.goodsPrice) {
                      if (orderItem.outboundNum < orderItem.num) {
                        orderItem.outboundNum += outboundItem.num
                      }
                    }
                  })
                })

                this.loading = false
              }
            })
          }
        }
      })
    },
    // 深克隆
    deepCopy (value) {
      if (value instanceof Function) return value
      else if (value instanceof Array) {
        var newValue = []
        for (let i = 0; i < value.length; ++i) newValue[i] = this.deepCopy(value[i])
        return newValue
      } else if (value instanceof Object) {
        var newValue = {}
        for (let i in value) newValue[i] = this.deepCopy(value[i])
        return newValue
      }
      return value
    },
    //取消订单
    orderCancel () {
      const _this = this;
      this.$modal.confirm('确认取消订单吗？').then(function () {
        cancelOrder(_this.order.id, { cancelReason: "运营取消订单" }).then(res => {
          _this.getOrderDetail()
          _this.$modal.msgSuccess("取消订单成功")
        })
      })
    },
    // 订单退款 订单详情
    openOrderRefundView () {
      this.afterSaleOrder = this.deepCopy(this.order)
      this.afterSaleOrder.refundFreightFlag = false;

      this.afterSaleOrder.orderItems.forEach(orderItem => {
        orderItem.orderItemNum = parseInt(orderItem.num)

        orderItem.num = 0;
      });

      this.orderRefundView = true;
    },
    // 订单退款
    orderRefund () {
      let applyRefundPrice = 0;

      let afterSaleItems = this.afterSaleOrder.orderItems.filter(i => {
        return i.num > 0
      }).map(orderItem => {
        let subTotal = orderItem.num * orderItem.goodsPrice;
        applyRefundPrice += subTotal;

        return {
          orderItemSn: orderItem.sn,
          skuId: orderItem.skuId,
          goodsId: orderItem.goodsId,
          goodsPrice: orderItem.goodsPrice,
          num: orderItem.num,
          goodsImage: orderItem.image,
          goodsName: orderItem.name,
          pack: orderItem.pack,
          expirationDate: orderItem.expirationDate,
          manufacturer: orderItem.manufacturer,
          simpleSpecs: orderItem.simpleSpecs,
          subTotal: subTotal
        }
      });

      let refundFreightPrice = null
      if (this.refundFreightFlag) {
        applyRefundPrice += this.afterSaleOrder.freightPrice
        refundFreightPrice = this.afterSaleOrder.freightPrice
      }

      const afterSale = {
        receipt: false,
        orderSn: this.afterSaleOrder.sn,
        tradeSn: this.afterSaleOrder.tradeSn,
        memberId: this.afterSaleOrder.memberId,
        memberName: this.afterSaleOrder.memberName,
        purchaserId: this.afterSaleOrder.purchaserId,
        purchaserName: this.afterSaleOrder.purchaserName,
        storeId: this.afterSaleOrder.storeId,
        storeName: this.afterSaleOrder.storeName,
        reason: '订单平台退款',
        serviceType: 'RETURN_MONEY',
        serviceStatus: 'APPLY',
        auditRemark: '平台退款',
        refundWay: 'ORIGINAL',
        flowPrice: this.afterSaleOrder.flowPrice,
        applyRefundPrice: applyRefundPrice,
        afterSaleItems: afterSaleItems
      }

      const _this = this;
      this.$modal.confirm('确认给订单"' + this.afterSaleOrder.sn + '退款"吗？').then(function () {
        console.log(afterSale)

        addAfterSale(afterSale).then(function (res) {
          _this.orderRefundView = false
          _this.$modal.msgSuccess("售后单创建成功")
        })
      })
      // const currentOrder = {
      //   id: this.order.id,
      //   cancelReason: '平台取消订单'
      // }
      // this.$modal.confirm('确认取消订单"' + this.order.sn + '"吗？')
      //   .then(function () {
      //     cancelOrder(currentOrder.id, currentOrder)
      //   })
    },
    unpayed () {
      const currentOrder = { id: this.order.id, paymentMethod: this.valuetype, receivableNo: this.payOrderNumber }
      const _this = this
      this.$modal.confirm('确认订单' + this.order.sn + '"用户未支付吗？').then(function () {
        updUnpay(currentOrder.id, currentOrder).then(res => {
          _this.getOrderDetail()
          _this.$modal.msgSuccess("设置订单未支付")
        })
      })
    },
    payed () {
      const currentOrder = { id: this.order.id, paymentMethod: this.valuetype, receivableNo: this.payOrderNumber }
      const _this = this
      this.$modal.confirm('确认订单' + this.order.sn + '"用户已支付吗？').then(function () {
        updPay(currentOrder.id, currentOrder).then(res => {
          _this.getOrderDetail()
          _this.$modal.msgSuccess("设置订单已支付")
        })
      })
    },
    // 修改为已发货
    shipped () {
      const currentOrder = {
        id: this.order.id, logisticsCode: this.valuetype,
        logisticsName: this.options.filter(i => i.code === this.valuetype)[0].name,
        logisticsNo: this.payOrderNumber,
      }
      const _this = this;
      this.$modal.confirm('确认订单' + this.order.sn + '"已发货了吗？').then(function () {
        updLogistics(currentOrder.id, currentOrder).then(res => {
          _this.getOrderDetail()
          _this.$modal.msgSuccess("订单发货成功")
        });
      })
    },
    // 确认收货
    completed () {
      const currentOrder = { id: this.order.id, orderStatus: 'DELIVERED' }
      const _this = this
      this.$modal.confirm('确认订单' + this.order.sn + '"用户已收货了吗？').then(function () {
        updOrderStatus(currentOrder.id, currentOrder).then(res => {
          _this.getOrderDetail()
          _this.$modal.msgSuccess("订单收货成功")
        })
      })
    },
    //订单重新推送到ERP
    handleRePush(){
      const _this = this
      this.$modal.confirm('确认将订单重新推送到ERP吗？').then(function () {
        updateInnerStatus(_this.order.sn, {innerStatus: 'RE_PUSH'}).then(response=>{
          _this.$modal.msgSuccess("已重新推送订单到ERP")
        })
      }).catch(function () {})
    },
  },
}
</script>

<style lang="scss" scoped>
.orderDetails_container {
  h1 {
    display: flex;
    margin: 30px 20px;
  }
  .orderDetails-orderInfo {
    padding: 0 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid rgba($color: #000000, $alpha: 0.1);
    span {
      margin: 10px 0;
      margin-right: 50px;
    }
  }
  .tableOrderList {
    padding: 0 20px;
    // overflow: hidden;
  }
  .issueOrderList {
    padding: 0 20px;
    // overflow: hidden;
  }
  .p {
    text-align: center;
    padding: 50px 0;
    span {
      margin-right: 50px;
    }
  }
  .dict-tag {
    div {
      display: inline;
    }
  }
  .order_status {
    padding-right: 100px;
    float: right;
    margin-bottom: 100px;
  }
}
::v-deep .el-dialog {
  top: 0;
  .tableOrderList {
    height: 500px;
    overflow-y: scroll;
  }
  .p {
    padding: 30px 0 0;
  }
}

.gifts {
  display: flex;
  max-height: 80vh;
  .left {
    width: 630px;
    margin-right: 10px;
    .item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 30px;
    }
    span:nth-child(1) {
      max-width: 70%;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    span:nth-child(2) {
      cursor: pointer;
      color: tomato;
    }
  }
  .right {
    width: 680px;
  }
}
</style>
